//
//  SEHospitalizeOrderListViewController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/16.
//

import UIKit

enum SEHospitalizeOrderListViewControllerFromType {
    case profile
    case payHospitalize
}

class SEHospitalizeOrderListViewController: SEBaseViewController {

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.tableFooterView = UIView()
            tableView.se_header = SERefreshHeader { [weak self] in self?.loadNewData() }
            tableView.se_footer = SERefreshFooter { [weak self] in self?.loadMoreData() }
            tableView.se_empty = SEEmptyView { [weak self] in self?.requestHospitalizeOrderList() }
            tableView.register(UINib(nibName: SEHospitalizeOrderListCell.className, bundle: nil), forCellReuseIdentifier: SEHospitalizeOrderListCell.reuseId)
        }
    }

    var viewModel = SEHospitalizeOrderListViewModel()

    init(with fromType: SEHospitalizeOrderListViewControllerFromType) {
        viewModel.fromType = fromType
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "问诊订单"
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.disablePopGesture = viewModel.fromType == .payHospitalize
        loadNewData()
    }

    override func popBack() {
        navigationController?.popToRootViewController(animated: true)
    }

    override func setupUI() {
        super.setupUI()

        viewModel.updateData = { [weak self] status in
            self?.tableView.se_empty?.allowShow = true
            self?.endRefreshing()
            switch status {
            case .success:
                self?.tableView.reloadData()
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.requestHospitalizeOrderList)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.cancelHandler = { status in
            switch status {
            case .success:
                self.requestHospitalizeOrderList()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.cancelHospitalizeOrder)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    func pushToHospitalizeOrderDetail() {
        let vc = SEHospitalizeOrderDetailViewController(with: viewModel.selectedListViewModel.model.id ?? "")
        vc.title = "订单详情"
        navigationController?.pushViewController(vc, animated: true)
    }

    func pushToReserConfirm() {
        let vc = SEConfirmReserveViewController(inquiryId: viewModel.selectedListViewModel.model.id ?? "", fromType: .hospitalizeOrderList)
        vc.paySuccessHandler = {
            self.requestHospitalizeOrderList()
        }
        vc.title = "确认预约"
        navigationController?.pushViewController(vc, animated: true)
    }

}

// MARK: - UITableViewDataSource, UITableViewDelegate

extension SEHospitalizeOrderListViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSections
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalizeOrderListCell.reuseId, for: indexPath) as! SEHospitalizeOrderListCell
        cell.delegate = self
        cell.updateCell(viewModel: viewModel.listViewModel(indexPath: indexPath))
        return cell
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.clear
        return view
    }

}

extension SEHospitalizeOrderListViewController: SEHospitalizeOrderListCellDelegate {
    func hospitalizeOrderListCell(_ cell: SEHospitalizeOrderListCell, didClickedDetailWith viewModel: SEHospitalizeOrderDetailViewModel) {
        self.viewModel.selectedListViewModel = viewModel
        pushToHospitalizeOrderDetail()
    }

    func hospitalizeOrderListCell(_ cell: SEHospitalizeOrderListCell, didClickedPayWith viewModel: SEHospitalizeOrderDetailViewModel) {
        self.viewModel.selectedListViewModel = viewModel
        pushToReserConfirm()
    }

    func hospitalizeOrderListCell(_ cell: SEHospitalizeOrderListCell, didClickedCancelWith viewModel: SEHospitalizeOrderDetailViewModel) {
        self.viewModel.selectedListViewModel = viewModel
        cancelHospitalizeOrder()
    }

}

// MARK: - APIRequest

extension SEHospitalizeOrderListViewController {
   @objc private func requestHospitalizeOrderList() {
        tableView.se_header?.beginRefreshing()
    }

    private func endRefreshing() {
        tableView.se_footer_hidden = false
        tableView.endHeaderRefreshing()
        tableView.endFooterRefreshing(hasMore: viewModel.hasMore)
    }

    private func loadNewData() {
        viewModel.page = 1
        viewModel.requestHospitalizeOrderList()
    }

    private func loadMoreData() {
        viewModel.page += 1
        viewModel.requestHospitalizeOrderList()
    }

    @objc private func cancelHospitalizeOrder() {
        viewModel.cancelHospitalizeOrder()
    }

}
